package me.kevinwalker.registar;

import me.kevinwalker.annotation.MongoDBScan;
import me.kevinwalker.bean.MongoDBFactoryBean;
import me.kevinwalker.core.handler.AnnotationClassHandler;
import me.kevinwalker.core.utils.MongoDBProxyUtil;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.List;

public class MongoDBBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {

    /**
     * 注册Bean定义
     *
     * @param importingClassMetadata  导入的类的元数据
     * @param registry                Bean定义注册器
     * @param importBeanNameGenerator 导入的Bean名称生成器
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        // 检查是否含有MongoDBScan注解
        if (importingClassMetadata.hasAnnotation(MongoDBScan.class.getName())) {
            // 获取所有注解属性
            MultiValueMap<String, Object> allAnnotationAttributes = importingClassMetadata.getAllAnnotationAttributes(MongoDBScan.class.getName());
            // 获取value属性列表
            List<Object> valueList = allAnnotationAttributes.get("value");
            // 创建MongoDB注解类列表
            final List<Class<?>> mongoDBAnnotationClassList = new ArrayList<>();
            valueList.forEach(packageDir -> {
                // 创建AnnotationClassHandler对象
                AnnotationClassHandler annotationClassHandler = new AnnotationClassHandler(packageDir.toString());
                // 获取MongoDB注解类列表,并添加到mongoDBAnnotationClassList列表中
                mongoDBAnnotationClassList.addAll(annotationClassHandler.getMongDBAnnotationClassList());
            });
            // 遍历mapper列表
            mongoDBAnnotationClassList.forEach(mapper -> {
                // 创建AbstractBeanDefinition对象
                AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
                // 设置beanClass为MongoDBFactoryBean类
                beanDefinition.setBeanClass(MongoDBFactoryBean.class);

                // 设置构造函数参数值为mapper类和通过getInstance方法获取的实例
                beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(mapper);
                beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(MongoDBProxyUtil.getInstance(mapper));
                // 注册beanDefinition到registry中
                registry.registerBeanDefinition(mapper.getName(), beanDefinition);
            });
        }
    }
}